<template>
  <div>
    <van-nav-bar title="用户登录" />
    <van-form
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-cell-group>
        <van-field
          v-model.trim="user.mobile"
          required
          label="手机号"
          placeholder="请输入手机号"
          :rules="[{ pattern: /^1[\d]{10}$/, message: '请输入11位正确手机号' }]"
        />
        <van-field
          v-model.trim="user.code"
          required
          type="password"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ pattern: /^\d{6}$/, message: '请输入6位正确验证码' }]"
        />
      </van-cell-group>
      <div class="btn-warp">
        <van-button
          plain
          type="info"
        >登录</van-button>
      </div>
    </van-form>
    <van-button
      plain
      type="info"
      @click='getuserInfo'
    >获取用户信息</van-button>
  </div>
</template>

<script>
import { login, getTokeninfo } from '../../api/user.js'
export default {
  name: 'login',
  data () {
    return {
      user: {
        mobile: '13912345678',
        code: '246810'
      }
    }
  },
  methods: {
    async getuserInfo () {
      const res = await getTokeninfo()
      console.log(res)
    },
    onFailed () {
      console.log('登录失败')
    },
    onSubmit () {
      this.hlogin()
    },
    async hlogin () {
      try {
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true
        })
        const res = await login(this.user.mobile, this.user.code)
        console.log(res)
        this.$toast.success('登录成功')
        this.$store.commit('mSetTokenInfo', res.data.data)
        const userInfo = await getTokeninfo()
        this.$store.commit('userInfo/msetUserInfo', userInfo.data.data)
        setTimeout(() => {
          // 通过this.$route.query获取地址栏敏感页面来源，登录成功后跳转回敏感页面
          const returnURL = this.$route.query.returnURL || '/'
          this.$router.push(returnURL)
        }, 1000)
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.btn-warp {
  padding: 0 20px;
  .van-button {
    background-color: #6db4fd;
    width: 100%;
    color: #fff;
  }
}
</style>
